package handler

import (
	"moon-exam7/cache"
	"moon-exam7/model"
	"moon-exam7/pkg"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

// 用户登录

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}

	redis_key := "user_login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码输错三次,禁止登录",
		})
		return
	}

	var user model.User
	err := model.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}

	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次,封禁两小时",
			})
			return
		}

		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}

// 角色权限添加

func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))

	roleNode := model.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	err := model.DB.Create(&roleNode).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

// 用户角色列表

func UserRoleList(c *gin.Context) {
	/*
		    select * from roles
			left join user_roles on user_roles.rid = roles.id
			where user_roles.uid = 1
	*/
	uid := c.Query("uid")

	var role []model.Role
	model.DB.Table("roles").
		Joins("left join user_roles on user_roles.rid = roles.id").
		Where("user_roles.uid = ?", uid).
		Debug().Find(&role)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表获取成功",
		"data": role,
	})
	return
}

// 角色权限列表

func RoleNodeList(c *gin.Context) {
	/*
		    select * from nodes
			left join role_nodes on role_nodes.nid = nodes.id
			where role_nodes.rid = 1
	*/
	rid := c.Query("rid")

	var node []model.Node
	model.DB.Table("nodes").
		Joins("left join role_nodes on role_nodes.nid = nodes.id").
		Where("role_nodes.rid = ?", rid).
		Debug().Find(&node)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表获取成功",
		"data": node,
	})
	return
}
